package br.inf.solutions.apresentacoes.ssp.control;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import br.com.vexillum.control.GenericControl;
import br.com.vexillum.util.HibernateUtils;
import br.com.vexillum.util.Return;
import br.com.vexillum.util.SpringFactory;
import br.inf.solutions.apresentacoes.ssp.model.Person;
import br.inf.solutions.apresentacoes.ssp.model.PostGraduation;
import br.inf.solutions.apresentacoes.ssp.model.SquarePostGraduation;

@Service
@Scope("prototype")
public class SquarePostGraduationController extends GenericControl<SquarePostGraduation> {

	public SquarePostGraduationController() {
		super(SquarePostGraduation.class);
	}
	
	@SuppressWarnings("unchecked")
	public Return sortListByPattern(){
		Return ret = new Return(true);
		PostGraduationController controller = SpringFactory.getController("postGraduationController", PostGraduationController.class, null);
		
		List<PostGraduation> allList = (List<PostGraduation>) controller.listAll().getList();
		List<PostGraduation> sortedAllList = new ArrayList<>();
		
		List<SquarePostGraduation> listEntity = (List<SquarePostGraduation>) HibernateUtils.initialize(data.get("listEntity"));
		List<SquarePostGraduation> sortedList = new ArrayList<>();
		
		HibernateUtils.initialize(listEntity);
		
		PostGraduation pattern = null;
		while(allList.size() > 0){
			for(Iterator<PostGraduation> i = allList.iterator(); i.hasNext();){
				PostGraduation post = i.next();
				post = HibernateUtils.materializeProxy(post);
				if(post.getPattern() == null || post.getPattern().equals(pattern)){
					sortedAllList.add(post);
					pattern = post;
					i.remove();
					break;
				}
			}
		}
		
		for(PostGraduation post : sortedAllList){
			for(SquarePostGraduation post2 : listEntity){
				if(post.equals(post2.getPostGraduation())){
					sortedList.add(post2);
					break;
				}
			}
		}
		
		ret.setList(sortedList);
		
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	public Return getNextPostGraduation(){
		Return ret = new Return(true);
		
		List<SquarePostGraduation> listEntity = (List<SquarePostGraduation>) data.get("listEntity");
		Person person = (Person) data.get("person");
		
		PostGraduationController controller = SpringFactory.getController("postGraduationController", PostGraduationController.class, null);
		PostGraduation pattern = controller.getPattern(person.getPost());
		
		List<SquarePostGraduation> resultList = new ArrayList<>();
		
		for(SquarePostGraduation sp : listEntity){
			if(pattern.equals(sp.getPostGraduation())){
				resultList.add(sp);
				break;
			}
		}
		ret.setList(resultList);
		return ret;
	}

}
